/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.message.MessageListActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.receiver.MiPushReceiver;
import cn.com.dhc.danlu.util.ActivityUtils;
import cn.com.dhc.danlu.util.AgentUtils;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.PushEngine;
import cn.com.dhc.danlu.util.SerializeCache;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.util.WeakHandler;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.request.login.LoginRequest;
import cn.com.hd.mall.web.webservices.entity.response.login.LoginResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * 欢迎画面
 *
 * @author MuWei
 * @version 1.00 2015/02/03 新建 w
 */
public class WelcomeActivity extends BaseActivity {

    private final int FLAG_GUIDEPAGE = 0X110;
    private final int FLAG_LOGINPAGE = 0X111;
    private final int FLAG_MAINPAGE = 0X112;
    /**
     * 登录成功后延迟跳转时间段
     */
    private final int LOGIN_REDIRECT_DELAY_TIMERSPAN = 2000;
    /**
     * 丹露用异步任务代理
     */
    //    private DanluTaskProxy danluTaskProxy;
    /**
     * 记录第几次安装
     */
    private int count = 0;

    private WeakHandler weakHandler;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        // 实例化画面控件
        setContentView (R.layout.layout_welcome);
        initHandler ();
        // 启动引导页
        startLinkPage ();
        // 应用程序versionName
        TextView textView1 = (TextView) findViewById (R.id.textView1);
        textView1.setText (CommonUtils.getAppVersioName (this));
        SerializeCache.getInstance ().saveCategoryIndex (-1);
    }

    private void initHandler () {
        weakHandler = new WeakHandler (new Handler.Callback () {
            @Override
            public boolean handleMessage (Message msg) {
                int what = msg.what;
                if (what == FLAG_GUIDEPAGE) {
                    Intent intent = new Intent ();
                    intent.setClass (WelcomeActivity.this, LinkPageActivity.class);
                    intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity (intent);
                    WelcomeActivity.this.finish ();
                } else if (what == FLAG_LOGINPAGE) {
                    // 跳转到登录画面
                    //                        ActivityUtils.startLoginActivity(delegate.getContext());
                    ActivityUtils.startLoginActivity (WelcomeActivity.this);
                    // 本画面结束
                    WelcomeActivity.this.finish ();
                } else if (what == FLAG_MAINPAGE) {

                }
                return true;
            }
        });
    }

    @Override
    protected String getActivityTitle () {
        return null;
    }

    /**
     * 启动引导页
     */
    private void startLinkPage () {
        // 记录是否跳转引导页
        SharedPreferences preferences = getSharedPreferences ("count", MODE_PRIVATE);
        count = preferences.getInt ("count", 0);
        // 判断程序与第几次运行，如果是第一次运行则跳转到引导页面
        if (count == 0) {
            Editor editor = preferences.edit ();
            // 存入数据
            editor.putInt ("count", ++count);
            // 提交修改
            editor.apply ();

            // 第一次安装
            Message message = Message.obtain ();
            message.what = FLAG_GUIDEPAGE;
            weakHandler.sendMessageDelayed (message, LOGIN_REDIRECT_DELAY_TIMERSPAN);
        } else {
            // 初始化
            init ();
        }
    }

    /**
     * 创建网络不可用对话框
     */
    private void createNetworkNotAvailableDialog () {
        // 创建Builder
        //        ViewDialog.Builder builder = new ViewDialog.Builder(delegate.getContext());
        ViewDialog.Builder builder = new ViewDialog.Builder (WelcomeActivity.this);
        // 设置标题
        builder.setTitle (R.string.prompt_label);
        // 设置信息
        builder.setMessage (R.string.to_network_setting_label);
        builder.setCancelable (false);
        // 设置Positive按钮点击监听
        builder.setPositiveButton (R.string.btn_ok, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                try {
                    // 进入无线网络配置界面 bug 5129 由于存在兼容问题
                    Intent intent1 = new Intent (Settings.ACTION_SETTINGS);
                    Intent intent2 = new Intent (Settings.ACTION_WIFI_SETTINGS);
                    boolean available = CommonUtils.isIntentAvailable (WelcomeActivity.this, intent1);
                    if (available) {
                        startActivity (intent1);
                    } else {
                        startActivity (intent2);
                    }
                } catch (Exception e) {
                    ToastUtil.getInstance ().show ("请检查网络");
                } finally {
                    // 对话框关闭
                    dialog.dismiss ();
                    // 本画面关闭
                    finish ();
                }
            }
        });

        // 设置Negative按钮点击监听
        builder.setNegativeButton (R.string.no_thanks_label, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                // 本画面关闭
                finish ();
                // 对话框关闭
                dialog.dismiss ();
            }
        });
        // 创建对话框并显示
        builder.create ().show ();
    }

    /**
     * 初始化
     */
    private void init () {
        // 检测是否连接到网络
        //        if (!AgentUtils.isNetworkConnected(delegate.getContext())) {
        if (!AgentUtils.isNetworkConnected (WelcomeActivity.this)) {
            // 网络未连接，创建网络不可用对话框
            createNetworkNotAvailableDialog ();
            // 逻辑终止
            return;
        }

        // 自动登录
        autoLogin ();
    }

    /**
     * 自动登录
     */
    private void autoLogin () {
        // 获取储存的用户名与密码
        String loginName = getPreferenceUtils ().getLoginName ();
        String password = getPreferenceUtils ().getPassword ();

        // 没有用户名与密码
        if (TextUtils.isEmpty (loginName) || TextUtils.isEmpty (password)) {
            Message message = Message.obtain ();
            message.what = FLAG_LOGINPAGE;
            weakHandler.sendMessageDelayed (message, 1000);
        } else {
            // 自动登录
            login (loginName, password);
        }
    }

    /**
     * 登录
     *
     * @param loginName
     *         用户名
     * @param password
     *         MD5加密后的密码
     */
    private void login (String loginName, String password) {
        // request
        LoginRequest form = new LoginRequest ();
        // 参数：用户名
        form.setUsername (loginName);
        // 参数：MD5加密后的密码
        form.setPassword (password);
        agent.getApi ()
                .login (form)
                .compose (OperatorUtils.<LoginResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<LoginResponse> () {
                    @Override
                    protected void onSuccess (LoginResponse model) {
                        // 登录成功
                        PushEngine.newInstance ().resumePush ();
                        PushEngine.newInstance ().setAlias (model.getUserId ());
                        PushEngine.newInstance ().setTopic (CommonConst.TOPIC_PREFIX + model.getCompanyId ());
                        PushEngine.newInstance ().setTopic (CommonConst.TAG_ENVELOP + model.getCompanyId ());

                        check (model);

                        // 开启账号统计
                        MobclickAgent.onProfileSignIn (model.getUserId ());
                        // 将用户数据保存到Application中
                        agent.setLoginUser (model);

                        getPreferenceUtils ().setUserId (model.getUserId ());
                        getPreferenceUtils ().setFullName (model.getFullName ());

                        skipActivtyLogic ();
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        redirectLoginActivity ();
                    }
                });
    }

    public void skipActivtyLogic () {
        if (MiPushReceiver.sIsLevelJump) {
            // 推送通知跳转到目标界面
            Intent messageListIntent = new Intent (this, MessageListActivity.class);
            messageListIntent.putExtra (MessageListActivity._TYPE_ADAPTER, MiPushReceiver.globalType);
            Intent mainIntent = new Intent (this, MainMenuActivity.class);
            Intent[] intents = new Intent[] {mainIntent, messageListIntent};
            startActivities (intents);
            MiPushReceiver.sIsLevelJump = false;
            finish ();
        } else {
            // 跳转至首页
            redirectMainActivity ();
        }
    }

    /**
     * 跳转至首页
     */
    private void redirectMainActivity () {
        // 跳转到首页画面
        ActivityUtils.startMainMenuActivity (WelcomeActivity.this);
        // 本画面结束
        finish ();
    }

    public void check (LoginResponse loginResponse) {
        if (TextUtils.isEmpty (loginResponse.getTelStatus ())) {
            loginResponse.setTelStatus ("1");
        }
    }

    /**
     * 跳转至登录界面
     */
    private void redirectLoginActivity () {
        // 跳转到登录画面
        ActivityUtils.startLoginActivity (WelcomeActivity.this);
        // 本画面结束
        finish ();
    }

    @Override
    protected void onDestroy () {
        if (null != weakHandler) {
            weakHandler.removeCallbacksAndMessages (null);
            weakHandler = null;
        }
        super.onDestroy ();
//        DanluApplication.getReWatcher ().watch (this);
    }
}